package com.lcxw.hxzbapi.controller.incomecontroller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lcxw.hxzbapi.entity.pojo.IncomeTotal;
import com.lcxw.hxzbapi.entity.pojo.Tixian;
import com.lcxw.hxzbapi.entity.pojo.YwpdChargeDetail;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.requestBean.GetMyTixianRecordReq;
import com.lcxw.hxzbapi.entity.requestBean.TixianApplyReq;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.IncomeTotalService;
import com.lcxw.hxzbapi.service.TixianService;
import com.lcxw.hxzbapi.service.YwpdChargeDetailService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbapi.tencentim.FeignService.ImManager;
import com.lcxw.hxzbapi.tencentim.common.ImCommand;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class TixianRealization {

    @Autowired
    private TencentImRealization tencentImRealization;
    @Resource
    TixianService tixianService;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    IncomeTotalService incomeTotalService;

    @Resource
    ImManager imManager;

    @Resource
    YwpdChargeDetailService ywpdChargeDetailService;


    public Response tixianApply(TixianApplyReq tixianApplyReq) {

        long userId = Long.parseLong(tixianApplyReq.getUserId());
        YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
        if (ywpdMember.getRealNameAuth() != 1) {
            return Response.error(ErrorCode.NO_PERMISSION, "未实名认证，无法申请提现");
        }

        if (ywpdMember.getSign() == 1) {
            return Response.error(ErrorCode.NO_PERMISSION_SUPPLEMENT, "您已加入公会，收入将转由公会发放，无法直接提现");
        }

        String type = tixianApplyReq.getType();
        String account = tixianApplyReq.getAccount();
        double tixian = tixianApplyReq.getTixian();
        String realName = tixianApplyReq.getRealName();

        IncomeTotal incomeTotal = incomeTotalService.selectByUserId(userId);
        if (incomeTotal == null) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "还没有任何收入记录");
        }
        double incomeEnable = incomeTotal.getIncomeEnable();
        if (tixian < 100 || incomeEnable < tixian) {
            return Response.error(ErrorCode.NOT_ENOUGH, "可提现金额不足，可提现金额必须大于100元，且提现金额不能高于可提现金额");
        }

        if (!type.equals("支付宝")) {
            return Response.error(ErrorCode.NOT_SUPPLY, "暂不支持该提现方式");
        }

        Tixian tixianRecord = new Tixian();
        tixianRecord.setUserId(userId);
        tixianRecord.setEnable(incomeEnable);
        tixianRecord.setTixian(tixian);
        tixianRecord.setType(type);
        tixianRecord.setAccount(account);
        tixianRecord.setTotal(incomeTotal.getIncomeTotal());
        tixianRecord.setStatus("0");
        tixianRecord.setAddTime(StringUtil.getDateTime());
        tixianRecord.setRealName(realName);
        tixianService.insert(tixianRecord);

        //将可提现金额减去申请提现的金额，然后更新到数据库
        incomeTotal.setIncomeEnable(StringUtil.formatDouble(incomeEnable - tixian));
        incomeTotalService.update(incomeTotal);
        return Response.ok();

    }

    //查询我的提现申请记录
    public Response getMyTixianRecord(GetMyTixianRecordReq getMyTixianRecordReq) {
        long userId = Long.parseLong(getMyTixianRecordReq.getUserId());
        int pageNum = getMyTixianRecordReq.getPageNum();
        String status = getMyTixianRecordReq.getStatus();
        if (StringUtil.isEmpty(status)) {
            status = null;
        }
        int pageSize = getMyTixianRecordReq.getPageSize();
        if (pageSize == 0) {
            pageSize = 10;
        }
        IPage<Tixian> tixianIPage = tixianService.selectByUserId(userId, status, pageNum, pageSize);
        int total = (int) tixianIPage.getTotal();
        List<Tixian> records = tixianIPage.getRecords();
        JSONObject data = new JSONObject();
        data.put("total", total);
        data.put("records", records);
        return Response.ok(data);

    }

    //admin模块查询提现申请记录
    public Response adminGetRecords(Long userId, String startTime, String endTime, String status,
        int pageNum,
        int pageSize) {
        IPage<Tixian> pages = tixianService
            .getList(userId, startTime, endTime, status, pageNum, pageSize);
        int total = (int) pages.getTotal();
        List<Tixian> records = pages.getRecords();
        JSONObject data = new JSONObject();
        data.put("total", total);
        data.put("records", records);

        return Response.ok(data);
    }

    public Response dealTixian(int id, String decision, String orderNumber, String reason) {

        Tixian tixian = tixianService.selectById(id);
        String desc="";
        if (decision.equals("1")) {
            desc="礼物收益: "+tixian.getTixian()+"已入账到你指定账户";
            tixian.setStatus(decision);
            tixian.setOrderNumber(orderNumber);
            tixianService.update(tixian);
            Long userId = tixian.getUserId();
            IncomeTotal incomeTotal = incomeTotalService.selectByUserId(userId);
            Double total = incomeTotal.getIncomeTotal();
            incomeTotal.setIncomeTotal(total - tixian.getTixian());
            incomeTotal.setIncomeFish(incomeTotal.getIncomeFish() + tixian.getTixian());
            incomeTotalService.update(incomeTotal);
        } else if (decision.equals("2")) {
            desc="审核不通过原因: "+reason;
            tixian.setStatus(decision);
            tixian.setReason(reason);
            tixianService.update(tixian);
            Long userId = tixian.getUserId();
            IncomeTotal incomeTotal = incomeTotalService.selectByUserId(userId);
            incomeTotal.setIncomeEnable(incomeTotal.getIncomeEnable() + tixian.getTixian());
            incomeTotalService.update(incomeTotal);
        }
        Response msg = new Response();
        msg.setCode(ImCommand.WITHDRAWAL_NOTICE);
        msg.setDesc(desc);
        msg.setData(reason);
        tencentImRealization.sendmsg(tencentImRealization.generateUserBody(JSON.toJSONString(msg),tixian.getUserId()+""));
        return Response.ok();
    }


    @Transactional
    public Response recharge(TixianApplyReq tixianApplyReq) {
        long userId = Long.parseLong(tixianApplyReq.getUserId());
        YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(userId);
        if (ywpdMember.getRealNameAuth() != 1) {
            return Response.error(ErrorCode.NO_PERMISSION, "未实名认证，无法充值");
        }
        if (ywpdMember.getSign() == 1) {
            return Response.error(ErrorCode.NO_PERMISSION_SUPPLEMENT, "您已加入公会，收入将转由公会发放，无法直接充值");
        }
        double tixian = tixianApplyReq.getTixian()/10;
        IncomeTotal incomeTotal = incomeTotalService.selectByUserId(userId);
        if (incomeTotal == null) {
            return Response.error(ErrorCode.DATA_NOT_EXIST, "还没有任何收入记录");
        }
        double incomeEnable = incomeTotal.getIncomeEnable();
        if (tixian < 1 || incomeEnable < tixian) {
            return Response.error(ErrorCode.NOT_ENOUGH, "可提现金额不足，可提现金额必须大于1，且提现金额不能高于可提现金额");
        }
        Tixian tixianRecord = new Tixian();
        tixianRecord.setUserId(userId);
        tixianRecord.setEnable(incomeEnable);
        tixianRecord.setTixian(tixian);
        tixianRecord.setType("幸运币");
        tixianRecord.setTotal(incomeTotal.getIncomeTotal());
        tixianRecord.setStatus("1");
        tixianRecord.setAddTime(StringUtil.getDateTime());
        tixianRecord.setAccount(userId+"");
        tixianService.insert(tixianRecord);
        //将可提现金额减去申请提现的金额，然后更新到数据库
        incomeTotal.setIncomeEnable(StringUtil.formatDouble(incomeEnable - tixian));
        incomeTotalService.update(incomeTotal);
        //这里生成唯一的订单id
        String outTradeNo = StringUtil.getOrderIdByUUId(1);
        //开始生成一条充值记录，插入到数据库中
        YwpdChargeDetail ywpdChargedetail = new YwpdChargeDetail();
        ywpdChargedetail.setUserId(userId);
        ywpdChargedetail.setOrderNo(outTradeNo);
        ywpdChargedetail.setChargeMode("钱包");
        ywpdChargedetail.setRmb(Float.valueOf(tixian+""));
        ywpdChargedetail.setCoin(Double.valueOf(tixian).intValue()*10);
        ywpdChargedetail.setContent("陌滋-"+ywpdChargedetail.getCoin()+"幸运币");
        ywpdChargedetail.setStatus("交易成功");
        ywpdChargeDetailService.addChargeDetail(ywpdChargedetail);
        //完成支付后，将用户充进的虚拟货币添加到用户数据中
        ywpdMemberService
                .updateCoinByUserId(ywpdChargedetail.getCoin(), ywpdChargedetail.getUserId());
        return Response.ok();
    }

}
